package cn.sylinx.horm.example.section7;

import java.lang.reflect.Method;
import java.util.Map;

import cn.sylinx.horm.core.SqlClient;
import cn.sylinx.horm.interceptor.Invocation;
import cn.sylinx.horm.proxy.Invoker;
import cn.sylinx.horm.proxy.command.CommandMethodMetadata;
import cn.sylinx.horm.proxy.command.interceptor.CommandInterceptor;
import cn.sylinx.horm.util.Tuple;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestCommandInterceptor implements CommandInterceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Object[] args = invocation.getArgs();
        CommandMethodMetadata methodMetadata = (CommandMethodMetadata) args[0];
        
        Method method = methodMetadata.getMethod();
        Class<?> interfaceClass = methodMetadata.getCommandInterface();
        
        if(interfaceClass == MyExample7Command.class && method.getName().equals("queryOne")) {
            
            Tuple tuple = (Tuple)args[1];
            String truelyDatasource = tuple.getObject(3);
            
            Invoker invoker = (Invoker)invocation.getTarget();
            SqlClient sqlClient = invoker.getClient(truelyDatasource);
            String dbtype = sqlClient.getDialect().getDbType().getValue();
            
            Map<String, Object> params = tuple.getObject(0);
            params.put("dbtype", dbtype);
            
            log.info("拦截MyExample7Command.queryOne方法，将当前dbtype存入参数");
            
        }

        return invocation.proceed();
    }

}
